<template>
  <div class="searchDiv">
    <div class="search-bar">
      <a-input
        v-model="content"
        placeholder="请输入关键字"
        class="content-input"
      />
      <a-button
        type="primary"
        @click="searchBlog"
        icon="search"
        class="query-btn"
      >
        搜索
      </a-button>
    </div>
    <div calss="result">
      <div
        class="result-content"
        @click="showContent(item.id)"
        v-for="item in data"
      >
        <div class="blog-title">{{ item.title }}</div>
        <div class="blog-content">
          <ul>
            <li v-for="str in item.parts" v-html="str"></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BlogSearch',
  data() {
    return {
      content: '',
      data: [],
    }
  },
  methods: {
    searchBlog() {
       this.$axios.post('/getBlogByKeyWorld', { content: this.content }).then(
        (val) => {
          if (val.status === 200) {
            val.data.forEach((item) => {
              let parts = [] // 包含的部分
              let flag = true
              let j = 0
              while (flag) {
                let i = item.content.indexOf(`${this.content}`, j)
                if (i > -1) {
                  let str = item.content.substring(i - 50, i + 50)
                  parts.push(
                    str.replace(
                      new RegExp(`${this.content}`, 'g'),
                      `<span style="color:red">${this.content}</span>`,
                    ),
                  )
                  j = i + 50
                } else {
                  flag = false
                }
              }
              item.parts = parts
            })
            this.data = val.data
            console.log(this.data)
          }
        },
      )
    },
    // 查看博客详细情况
    showContent(id) {
      this.$router.push({
        path: '/home/blogContent',
        query: {
          id: id,
        },
      })
    },
  },
}
</script>

<style scoped lang="less">
.content-input {
  width: 200px;
}
.query-btn {
  margin-left: 50px;
}
.search-bar {
  margin-bottom: 20px;
}
.blog-title {
  cursor: pointer;
  font-size: 18px;
  font-weight: 100;
  color: #000;
}
.blog-content {
  ul {
    list-style: none;
    li {
      margin-bottom: 20px;
    }
  }
}
</style>
